//
//  HistoryManager.swift
//  YoruNeko
//
//  Created by Kotori on 2021/6/24.
//

import Foundation

class HistoryManager {
    //数据读写工具对象
    private static let io = YRNKDataStore()
    private static let encoder = JSONEncoder()
    private static let decoder = JSONDecoder()
    //private static var isDirty = false
    //当前所缓存的历史记录的用户名
    private static var cachedUserUuid = UserManager.currUserUuid
    //历史记录数组，启动时从存储读取，应用关闭时写入到存储
    private static var cachedHistoryList: [History] = []
    //对于同样的两个URL，是否生成新的浏览记录 时间间隔为300s
    private static var cachedInterval = 300.0
    //空历史记录Hash表，程序启动时为空
    private static var cachedHashHistory: [String: History] = [:]
    
    
    static func getCachedHistoryList()->[History] {
        return cachedHistoryList
    }
    
    //根据UUID获取历史列表
    static func readHistoryList(of uuid: UUID) throws -> [History] {

        //如果历史记录缓存列表为空, 或者要读取的用户与上次读取的用户不同（切换用户后） 开始从存储中读取
        if !(uuid==cachedUserUuid) || cachedHistoryList.isEmpty  {
            if let json = io.readFromStorage(user_uuid: uuid, srcType: .history) {
                cachedHistoryList = try decoder.decode([History].self, from: json.rawData())
            }
        }
        return cachedHistoryList
    }
    
    //添加历史记录
    static func addHistory(title: String, url: String, pngData favicon: Data?) {
        if UserManager.currUserMgr.getNoHistory(){
            return
        }
        if title.isEmpty || url.isEmpty {
            return
        }
        //生成当前时间
        let currDate = Date()
        //即将插入对象
        let toInsert = History(faviconData: favicon, date_added: currDate, title: title, url: url)
        
        if let cachedHistory = cachedHashHistory[url] {
            if cachedHistory.date_added.distance(to: currDate) < cachedInterval {
                //本次应用程序会话中已经访问过该URL, 且时间间隔小于300秒
                if let index = cachedHistoryList.firstIndex(where: {$0.url == url}) {
                    cachedHistoryList.remove(at: index)
                }
            }
            //cachedHashHistory["url"]?.date_added = currDate
        }
        //头插入，头插法链表更好
        cachedHashHistory[url] = toInsert
        cachedHistoryList.insert(toInsert, at: 0)
        
        print("HistoryManager: Added \(cachedHistoryList[0].title) - \(cachedHistoryList[0].url)")
    }
    
    //保存内存中的历史记录到文件中，切换用户时、退出应用时调用。
    static func saveHistoryList() throws -> Bool {
        encoder.outputFormatting = .prettyPrinted
        let historyJsonData = try encoder.encode(cachedHistoryList)
        let json = try JSON.init(data: historyJsonData)
        return io.writeToStorage(user_uuid: cachedUserUuid, srcType: .history, jsonObj: json)
    }
    
    static func getRecentHistoryList(limit:Int) -> [History]{
        if limit >= cachedHistoryList.count {
            return cachedHistoryList
        }else{
            let subArray = Array(cachedHistoryList[0...limit-1])
            return subArray
        }
    }
    
    static func deleteHistoryList(uuidList: [UUID]){
        let deleteUuidSet = Set(uuidList)
        cachedHistoryList.removeAll(where: {deleteUuidSet.contains($0.id)})
    }
    
    
    static func deleteHistory(uuid: UUID){
        if let index = cachedHistoryList.firstIndex(where: {
            $0.id == uuid
        }){
            cachedHistoryList.remove(at: index)
        }
    }
    
    static func deleteAll(){
        cachedHistoryList.removeAll()
        cachedHashHistory.removeAll()
    }
    
    static func refresh() {
        do {
            if try saveHistoryList() {
                deleteAll()
                cachedUserUuid = UserManager.currUserUuid
            }
            try cachedHistoryList = readHistoryList(of: cachedUserUuid)
        } catch {
            
        }
    }
    
    static func updateHistoryFavicon(url: String, faviconData: Data?) {
        if let _ = cachedHashHistory[url] {
            cachedHistoryList[cachedHistoryList.firstIndex(where: {$0.url == url})!].faviconData = faviconData
        }
    }
}
